/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package it.univaq.iw.jweb;

import it.univaq.iw.jweb.data.Curriculum;
import it.univaq.iw.jweb.data.DataAccess;
import it.univaq.iw.jweb.data.Province;
import it.univaq.iw.jweb.data.Servizio;
import it.univaq.iw.jweb.utils.ControlsHelpers;
import it.univaq.iw.jweb.utils.SecurityHelpers;
import it.univaq.iw.jweb.utils.TemplateManager;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author stefano
 */
public class ModificaAnagrafica extends HttpServlet {

    private TemplateManager tpl;
    private DataAccess da;

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);

        da = DataAccess.getInstance();

        tpl = TemplateManager.getInstance(getServletContext());
        tpl.setOutlineTemplate("outline");
        tpl.setDefaultData("author", "Del Vecchio - Bevini - Delfino");
        tpl.setDefaultData("homepage_url", "home");
        tpl.setDefaultData("completo",true);
        tpl.setDefaultData("logged", true);
        tpl.setDefaultData("servizi", da.searchServiziGruppo("candidato"));
    }

    private void selezionaServizi (String email) throws ServletException {

        List<Servizio> servizi = da.searchServiziGruppo(da.searchNomeGruppo(email));

        /* preparo i servizi in base allo stato del candidato */
        Iterator<Servizio> it = servizi.iterator();
        while (it.hasNext()) {
            Servizio servizio = it.next();
            if (da.curriculumCompletoByMail(email)) { /* curriculum completato */

                if (servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                        || (da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("inserisciPreferenze"))) {

                    it.remove();

                } else if(servizio.getNome().equalsIgnoreCase("inserisciCurriculum")
                        || (!da.hasPreferences(email) && servizio.getNome().equalsIgnoreCase("modificaPreferenze"))) {

                    it.remove();
                }

            } else { /* curriculum incompleto */

                if (servizio.getNome().equalsIgnoreCase("inserisciPreferenze")
                        || servizio.getNome().equalsIgnoreCase("modificaPreferenze")
                        || servizio.getNome().equalsIgnoreCase("modificaCurriculum")
                        || servizio.getNome().equalsIgnoreCase("visualizzaCurriculum")
                        || servizio.getNome().equalsIgnoreCase("eliminaCurriculum")) {

                    it.remove();
                }
            }
        }
        tpl.setDefaultData("servizi", servizi);

    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        HttpSession s = SecurityHelpers.checkSession(request);

        if (s == null) {

            response.sendRedirect("home");

        } else {

            selezionaServizi(s.getAttribute("email").toString());
            PrintWriter out = response.getWriter();

            try {

                Map datamodel = tpl.getDefaultDataModel();
                tpl.setDefaultData("hasPreferences",da.hasPreferences(s.getAttribute("email").toString()));

                if (!request.getParameterMap().containsKey("t")) {

                    int idCurr = da.searchIdCurriculumByMail(s.getAttribute("email").toString());
                    Curriculum curr = da.searchCurriculumById(idCurr);

                    datamodel.put("provincie", Province.values());
                    datamodel.put("curriculum", curr);
                    datamodel.put("action", "modificaAnagrafica?t=m");
                    tpl.process("modificaAnagrafica", datamodel, out);
                    out.close();
                    return;

                } else {

                    /* controllo le lunghezze dei campi inseriti */
                    if (!(request.getParameter("nomeCandidato").length() > 0
                            && request.getParameter("cognomeCandidato").length() > 0
                            && request.getParameter("indirizzo").length() > 0
                            && request.getParameter("cap").length() > 0
                            && request.getParameter("citta").length() > 0
                            && request.getParameter("email").length() > 0
                            && ControlsHelpers.controllaCAP(request.getParameter("cap"))
                            && ControlsHelpers.isDateValid(request.getParameter("dataDiNascita")) != null
                            && !request.getParameter("provincia").equalsIgnoreCase("Provincia"))
                            && ControlsHelpers.controllaNumeroTelefono(request.getParameter("telefono"))) {

                        tpl.setDefaultData("email", s.getAttribute("email").toString());
                        datamodel.put("messaggio", "ATTENZIONE: Inserisci i dati correttamente.");
                        datamodel.put("provincie", Province.values());
                        datamodel.put("curriculum", new Curriculum(request.getParameter("nomeCandidato"),
                                request.getParameter("cognomeCandidato"),
                                ControlsHelpers.isDateValid(request.getParameter("dataDiNascita")),
                                request.getParameter("sesso"),
                                request.getParameter("cap"),
                                request.getParameter("indirizzo"),
                                request.getParameter("citta"),
                                request.getParameter("provincia"),
                                request.getParameter("telefono"),
                                request.getParameter("email"),
                                request.getParameter("automunito")));

                        datamodel.put("action", "modificaAnagrafica");
                        tpl.process("modificaAnagrafica", datamodel, out);
                        out.close();
                        return;
                    }

                    if (da.modificaCurriculum(new Curriculum(request.getParameter("nomeCandidato"),
                                request.getParameter("cognomeCandidato"),
                                ControlsHelpers.isDateValid(request.getParameter("dataDiNascita")),
                                request.getParameter("sesso"),
                                request.getParameter("cap"),
                                request.getParameter("indirizzo"),
                                request.getParameter("citta"),
                                request.getParameter("provincia"),
                                request.getParameter("telefono"),
                                request.getParameter("email"),
                                request.getParameter("automunito")), s.getAttribute("email").toString())){

                        da.completaCurriculum(new Integer(da.searchIdCurriculumByMail(s.getAttribute("email").toString())).toString());

                        response.sendRedirect("modificaCurriculum");
                        
                    } else {
                        datamodel.put("messaggio", "Modifica non effettuata.");
                        tpl.process("home", datamodel, out);
                        out.close();
                        return;

                    }
                }

            } finally {

                out.close();

            }
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
